package com.vote.www.controller;


import com.vote.www.domain.Czjvote;
import com.vote.www.domain.Czjvotenum;
import com.vote.www.domain.Czjweixinvote;
import com.vote.www.domain.vo.WeixinInfo;
import com.vote.www.service.CzjuserinfoService;
import com.vote.www.service.CzjvoteService;
import com.vote.www.service.RecommendpicService;
import com.vote.www.service.WeixininfoService;
import com.vote.www.utils.UUIDUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/vote")
public class CzjvoteController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(CzjvoteController.class);
	public CzjvoteController() {
	}
 

	/**
	 * czj_vote 投票表保存
	 * 
	 * @param pid	获取微信用户信息的code
	 * @param userinfoId 被投票人id
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteSave.do")
	public synchronized void save(
			@RequestParam(required = true) String pid,
			@RequestParam(required = true) String userinfoId,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      
    	//投票截止时间
    	String strlast = "2017-05-26 00:00:00";
    	//投票数量1
    	String  voteNum1 = "";
    	Map<String,Object> paramvote = new HashMap<String, Object>();
    	paramvote.put("userinfoId", userinfoId);
    	voteNum1 = String.valueOf(czjuserinfoService.voteNum(paramvote));
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	Date voteEndDate = sdf.parse(strlast);			
		long betweenTrue = new Date().getTime() - voteEndDate.getTime();
		long remainMin= (voteEndDate.getTime() - new Date().getTime())/1000/60;
		Map<String,Object> map = new HashMap<String,Object>();
		if(betweenTrue>=0){
			remainMin =0;		
			map.put("remainMin", remainMin);
			jsonResult(0,voteNum1,"投票时间已经过期",map,response);
			return;
		}
		
		
		WeixinInfo weixinInfo = null;
		try {
			 weixinInfo = weixininfoService.getWeixinInfo(pid);
		/*	Map<String,Object> map = weixininfoService.getWeixinGongzhonghao(pid);
			if(Integer.valueOf(String.valueOf(map.get("subscribe")))==1){
				log.error("log error:投票失败,错误用户code值不正确！");
				jsonResult(0,"98","投票失败,请关注公众号后再投票！","",response);
				return;
			}*/
			if(weixinInfo==null){
				log.error("log error:投票失败,错误用户code值不正确！");
                jsonResult(0,"200","投票失败,错误用户code值不正确！",map,response);
                return;
            }
            if(weixinInfo.getUpdate()!=null&&weixinInfo.getUpdate()==1){
				recommendpicService.saveWeixininfo(weixinInfo);
			}

			pid = weixinInfo.getOpenid();
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult(0,"200","投票失败,"+e.getMessage(),map,response);
			log.error("投票失败",e);
			return ;

		}


		Czjweixinvote czjweixinvote = new Czjweixinvote();
		czjweixinvote.setOpenid(weixinInfo.getOpenid());
		czjweixinvote.setNickname(weixinInfo.getNickname());
		czjweixinvote.setSex(String.valueOf(weixinInfo.getSex()));
		czjweixinvote.setProvince(weixinInfo.getProvince());
		czjweixinvote.setCity(weixinInfo.getCity());
		czjweixinvote.setCountry(weixinInfo.getCountry());
		czjweixinvote.setHeadimgurl(weixinInfo.getHeadimgurl());			
		String[] privilege = weixinInfo.getPrivilege();			
		if(privilege.length>0){	
		StringBuffer sb = new StringBuffer();
		String privilegestr = null;
		for(String str : privilege){
			sb.append(str);
			sb.append(",");
		}			
			privilegestr  =  sb.substring(0,sb.length()-1);
			czjweixinvote.setPrivilege(privilegestr);
		}
		czjweixinvote.setUnionid(weixinInfo.getUnionid());

		
		
		
		
		Czjvote czjvote = new Czjvote();
           String  voteNum = "";
		   String message="投票成功。";
			if("undefined".equals(pid.toLowerCase())){
				jsonResult(0,"投票失败,稍后再投","pid,传的是undefined",map,response);
				return ;
			}
			String createId = request.getParameter("createId");
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("pid", pid);
			param.put("userinfoId", userinfoId);
			//投票数量表
			Czjvotenum czjvotenum = new Czjvotenum();
			czjvotenum.setUserInfoId(userinfoId);
		try {         
			if(czjvote.getVoteId()!=null&&!czjvote.getVoteId().equals("")){
				// 编辑
//				czjvoteService.updateCzjvote(czjvote);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_vote 投票表", "voteId="+czjvote.getVoteId()));
			} else {
				// 新增
				Date now = new Date();
				Czjvote czjvotePid = czjvoteService.getPidNew(param);
				if(!"".equals(createId) && createId !=null){
				czjvote.setCreateId(Integer.valueOf(createId));
				}
				//如果为空直接插入,不为空,大于4小时能插入
				if(czjvotePid==null){
					if(!"".equals(pid)){
						czjvote.setPid(pid);
					}	
					if(!"".equals(userinfoId)){
						czjvote.setUserinfoId(Integer.valueOf(userinfoId));
					}	
					czjvote.setCreatetime(now);
					czjvoteService.insertCzjvote(czjvote);
					//插入微信信息
					czjweixinvote.setVoteId(czjvote.getVoteId());
					czjvoteService.insertCzjweixinvote(czjweixinvote);
					voteNum = String.valueOf(czjuserinfoService.voteNum(param));
					//voteNum等于0,即没有有记录
					if("0".equals(voteNum)){
						czjvotenum.setVoteNum(1);
						czjvoteService.insertCzjvotenum(czjvotenum);
						voteNum = "1";
					}else{
						int num = Integer.valueOf(voteNum);
						num++;
						czjvotenum.setVoteNum(num);
						czjvoteService.updateCzjvotenum(czjvotenum);
						voteNum =String.valueOf(num); 
					}					
					jsonResult(1,voteNum,message,map,response);
				}else{
					Date old = czjvotePid.getCreatetime();
					System.out.println(now.getTime()/1000);
					System.out.println(old.getTime()/1000);
					Long between = (now.getTime()-old.getTime())/1000;
					System.out.println(between);
					if(between>=14400){
						if(!"".equals(pid)){
							czjvote.setPid(pid);
						}	
						if(!"".equals(userinfoId)){
							czjvote.setUserinfoId(Integer.valueOf(userinfoId));
						}	
						czjvote.setCreatetime(now);
						czjvoteService.insertCzjvote(czjvote);
						//插入微信信息
						czjweixinvote.setVoteId(czjvote.getVoteId());
						czjvoteService.insertCzjweixinvote(czjweixinvote);
						voteNum = String.valueOf(czjuserinfoService.voteNum(param));
						//voteNum等于0,即没有有记录
						if("0".equals(voteNum)){
							czjvotenum.setVoteNum(1);
							czjvoteService.insertCzjvotenum(czjvotenum);
							voteNum = "1";
						}else{
							int num = Integer.valueOf(voteNum);
							num++;
							czjvotenum.setVoteNum(num);
							czjvoteService.updateCzjvotenum(czjvotenum);
							voteNum =String.valueOf(num); 
						}	
						jsonResult(1,voteNum,message,map,response);
					}else{
						voteNum = String.valueOf(czjuserinfoService.voteNum(param));
					  message="投票失败,4小时内不能重复投票。";	
					  jsonResult(0,voteNum,message,map,response); 
					}									
				}				 				
				
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_vote 投票表", "voteId="+czjvote.getVoteId()));
			}
			//responseSucess(response);
		} catch (Exception e) {		
			e.printStackTrace();
			voteNum = String.valueOf(czjuserinfoService.voteNum(param));
			jsonResult(0,voteNum,"投票失败,系统异常",map,response);
			log.error("投票失败,系统异常",e);
			
		}
	}

    @RequestMapping("savevotenum.do")
    public String detail11(@RequestParam(required = true) String id,
    		               @RequestParam("voteNum") String  voteNum,
                      String msg,
                      HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) throws UnsupportedEncodingException {
	    	if("".equals(voteNum)){	    		
	    		String msg1 = "投票数量不能为空和请输入正整数";
	    		msg1=URLEncoder.encode(msg1,"utf-8");
	    		return "redirect:/approve/list.do?id="+id+"&msg="+msg1;
	    	}
  	   
			//投票数量表
			Czjvotenum czjvotenum = new Czjvotenum();
			czjvotenum.setUserInfoId(id);
			czjvotenum.setVoteNum(Integer.valueOf(voteNum));
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("userInfoId",id);
        try {
        	if("0".equals(voteNum)){
        		//删除
        		czjvoteService.deleteCzjvotenumtrue(param);
        	}else{
        		//插入或更新
        		Czjvotenum czjvotenum2 = czjvoteService.getCzjvoteNum(param);        		    		
        		  if(czjvotenum2==null){
        			  czjvoteService.insertCzjvotenum(czjvotenum);  
        		  }else{        			  
        			  czjvoteService.updateCzjvotenum(czjvotenum);       		
        		  }
        		
        	}
        	
        	
        } catch (Exception e) {
            e.printStackTrace();
        }
		return "redirect:/approve/list.do?id="+id;
    }  


    @RequestMapping("savevotenumBack.do")
    public String detaifdsfasd(@RequestParam(required = true) String id,
    		               @RequestParam("voteNum") String  voteNum,
                      String msg,
                      HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) {
    	    String message ="";
    	    Map<String, Object> messageParam = new HashMap<String, Object>();
    	    
    	    StringBuffer sb = new StringBuffer();
    	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
        	if(!voteNum.equals("")){
	           	Map<String, Object> param = new HashMap<String, Object>();
	           	param.put("userinfoId", id);           	
        	  int edit = Integer.valueOf(voteNum);
        	  int db = czjuserinfoService.voteNum(param);
        	  int insert = edit-db;
        	  int delete = db-edit;
        	  if(edit>db){
        		  for(int i=0;i<insert;i++){
        	    	 sb.append("('");
        			 sb.append(UUIDUtils.getUUID()+"','");
        			 sb.append(UUIDUtils.getUUID()+"',");
        			 sb.append(id+",'");
        			 sb.append(sdf.format(new Date())+"',");
        			 sb.append("1");
        			 sb.append("),");
        		  }
        		  message = sb.substring(0, sb.length()-1);
        		  messageParam.put("message", message);
        		  czjvoteService.insertCzjvoteBack(messageParam);
        	  }
        	  if(edit<db){
        			 messageParam.put("message", delete);
        			 czjvoteService.deleteCzjvoteBack(messageParam);         		 
        	  }	
        		
        	}          
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/approve/detail.do?id="+id;
    }  
    
  
    @RequestMapping("savevotenumrecover.do")
    public void detaifdsfasd1(
                      HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) {
        try {
        	String password  = req.getParameter("password");
        	if("czj".equals(password)){
        	czjvoteService.deleteCzjvotenum();
        	List<String> list = czjvoteService.CzjvoteUserInfoId();
        	for(String  str: list){
        		Map<String,Object> map = new HashMap<String, Object>();
        		map.put("userInfoId", str);
        		czjvoteService.insertUserInfoIdAndVotenum(map);
        	}      	
        	jsonResult(1,"","数据回复成功","",resp);
        	}else{
        	jsonResult(0,"","数据回复失败","",resp);
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }     
    


 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param czjvote
	 * @return
	 */	private Map<String,Object> toMap(Czjvote czjvote){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(czjvote.getVoteId()!=null&&!czjvote.getVoteId().equals("")){
			map.put("voteId", czjvote.getVoteId());
		}
		/*if(czjvote.getVotemy()!=null&&!czjvote.getVotemy().equals("")){
			map.put("votemy", czjvote.getVotemy());
		}
		if(czjvote.getVoteother()!=null&&!czjvote.getVoteother().equals("")){
			map.put("voteother", czjvote.getVoteother());
		}*/
		if(czjvote.getCreatetime()!=null&&!czjvote.getCreatetime().equals("")){
			map.put("createtime", czjvote.getCreatetime());
		}
		if(czjvote.getRemark()!=null&&!czjvote.getRemark().equals("")){
			map.put("remark", czjvote.getRemark());
		}
		if(czjvote.getCreateId()!=null&&!czjvote.getCreateId().equals("")){
			map.put("createId", czjvote.getCreateId());
		}
		if(czjvote.getExt2()!=null&&!czjvote.getExt2().equals("")){
			map.put("Ext2", czjvote.getExt2());
		}
		if(czjvote.getExt3()!=null&&!czjvote.getExt3().equals("")){
			map.put("Ext3", czjvote.getExt3());
		}      
		return map;
	}
   



   
      
	@Resource
	private CzjuserinfoService czjuserinfoService;
	 
	@Resource
	private CzjvoteService czjvoteService;
	@Resource
	private WeixininfoService weixininfoService;

	@Autowired
	private RecommendpicService recommendpicService;



}